from django.db import transaction
from django.shortcuts import render
from rest_framework import permissions
from rest_framework.views import APIView
from utils.customer_modelviewset import CustomerViewSet
from utils import response_error, response_ok
from .models import Category, Upload
from .serializers import CategorySerializer, UploadSerializer


# Create your views here.


class CategoryViewSet(CustomerViewSet):
    permission_classes = [permissions.IsAdminUser, ]
    queryset = Category.objects.filter()
    serializer_class = CategorySerializer


class UploadViewSet(CustomerViewSet):
    # queryset = Upload.objects.filter()
    queryset = Upload.objects.filter()
    serializer_class = UploadSerializer

    def create(self, request, *args, **kwargs):
        file = request.FILES.get('file')
        if not file:
            return response_error(u'未找到上传的数据')
        try:
            with transaction.atomic():
                upload = Upload.objects.upload(request.user, file)
        except Exception as e:
            import traceback
            traceback.print_exc()
            return response_error(str(e))
        return response_ok()
